﻿using System.Diagnostics;
using System.Text.RegularExpressions;
using SMCL.Core.Utils.Java;

namespace SMCL.Utils.Java
{
    public static partial class GetJavaInfo
    {
        [GeneratedRegex("version \"(.*?)\"")]
        private static partial Regex VersionRegex();
        [GeneratedRegex("Runtime Environment ?(.*?) ?\\(build")]
        private static partial Regex VendorRegex();
        [GeneratedRegex("(\\d{4}-\\d{2}-\\d{2})")]
        private static partial Regex BuildDateRegex();
        public static JavaInfo? TryGet(string path)
        {
            var proc = new Process();
            proc.StartInfo.FileName = path;
            proc.StartInfo.ArgumentList.Add("-version");
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.CreateNoWindow = true;
            proc.Start();
            proc.WaitForExit();
            var stdout = proc.StandardOutput.ReadToEnd();
            var stderr = proc.StandardError.ReadToEnd();
            var output = string.IsNullOrWhiteSpace(stdout) ? stderr : stdout;
            var versionResult = VersionRegex().Match(output);
            var vendorResult = VendorRegex().Match(output);
            var buildDateResult = BuildDateRegex().Match(output);
            if(!versionResult.Success || !versionResult.Success)
                return null;
            var ret = new JavaInfo()
            {
                Version = Version.Parse(versionResult.Groups[1].Value.Replace('+', '.').Replace("-", ".").Replace('_','.')),
                Vendor = vendorResult.Groups[1].Value,
                BuildDate = buildDateResult.Success ? DateOnly.Parse(buildDateResult.Groups[1].Value) : null,
                Address = path
            };
            //for java "1.8"
            if(ret.Version.Major == 1 && ret.Version.Minor != 0)
                ret.Version = new(ret.Version.Minor, 0, ret.Version.Build, ret.Version.Revision);
            if (ret.Vendor.StartsWith('(') && ret.Vendor.EndsWith(')'))
                ret.Vendor = ret.Vendor[1..^1];
            return ret;
        }
    }
}
